package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.BaseUserOrganization;
import com.ruoyi.system.domain.vo.BaseTournamentPersonnelAttendanceVO;
import com.ruoyi.system.domain.vo.BaseTournamentPersonnelResponseVO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IBaseUserOrganizationService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.BaseTournamentPersonnelMapper;
import com.ruoyi.system.domain.BaseTournamentPersonnel;
import com.ruoyi.system.service.IBaseTournamentPersonnelService;

/**
 * 赛事工作人员Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-16
 */
@Service
public class BaseTournamentPersonnelServiceImpl extends ServiceImpl<BaseTournamentPersonnelMapper, BaseTournamentPersonnel> implements IBaseTournamentPersonnelService
{
    @Autowired
    private BaseTournamentPersonnelMapper baseTournamentPersonnelMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    LoginUserSetUtil loginUserSetUtil;
    @Autowired
    private IBaseUserOrganizationService iBaseUserOrganizationService;

    /**
     * 查询赛事工作人员
     * 
     * @param id 赛事工作人员主键
     * @return 赛事工作人员
     */
    @Override
    public BaseTournamentPersonnel selectBaseTournamentPersonnelById(Long id)
    {
        return baseTournamentPersonnelMapper.selectBaseTournamentPersonnelById(id);
    }

    /**
     * 查询赛事工作人员列表
     * 
     * @param baseTournamentPersonnel 赛事工作人员
     * @return 赛事工作人员
     */
    @Override
    public List<BaseTournamentPersonnel> selectBaseTournamentPersonnelList(BaseTournamentPersonnel baseTournamentPersonnel)
    {
        List<BaseTournamentPersonnel> baseTournamentPersonnels = baseTournamentPersonnelMapper.selectBaseTournamentPersonnelList(baseTournamentPersonnel);
        if (CollUtil.isEmpty(baseTournamentPersonnels)) {
            return CollUtil.newArrayList();
        }
        List<Long> userIds = baseTournamentPersonnels.stream().map(BaseTournamentPersonnel::getUserId).collect(Collectors.toList());
        List<SysUser> sysUsers = sysUserMapper.selectUserByIds(userIds);
        Map<Long, SysUser> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity(), (k, v) -> k));

        baseTournamentPersonnels.forEach(vo ->{
            SysUser sysUser = userMap.get(vo.getUserId());
            if (Objects.nonNull(sysUser)){
                vo.setCreateUserName(sysUser.getUserName());
                vo.setPhone(sysUser.getPhonenumber());
            }
        });
        return baseTournamentPersonnels;
    }

    /**
     * 新增赛事工作人员
     * 
     * @param baseTournamentPersonnel 赛事工作人员
     * @return 结果
     */
    @Override
    public int insertBaseTournamentPersonnel(BaseTournamentPersonnel baseTournamentPersonnel)
    {
        loginUserSetUtil.populateFields(baseTournamentPersonnel, 1);

        AssertUtil.notEmpty(baseTournamentPersonnel.getPhone(),"手机号不能为空");
        SysUser info = sysUserMapper.checkPhoneUnique(baseTournamentPersonnel.getPhone());
        //注册手机号
        if(Objects.isNull(info)){
            info = new SysUser();
            info.setUserName("权限注册用户_"+ UUID.randomUUID().toString().substring(0, 8));
            info.setNickName(info.getUserName());
            //用户信息为空则直接创建用户并登录 通过accessToken获取用户基本信息
            if (StringUtils.isNotEmpty(baseTournamentPersonnel.getPhone())){
                info.setNickName(baseTournamentPersonnel.getPhone());
            }
            info.setContestId(baseTournamentPersonnel.getContestId());
            info.setOrganizationId(baseTournamentPersonnel.getOrganizationId());
            info.setPhonenumber(baseTournamentPersonnel.getPhone());
            info.setPassword(SecurityUtils.encryptPassword("123456"));
            info.setUserId(getUserIds());
            sysUserMapper.insertUser(info);
        }

        if (baseTournamentPersonnel.getLevel()==0) {
            //校验当前userid是否存在其他权限
            LambdaQueryWrapper<BaseTournamentPersonnel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseTournamentPersonnel::getUserId, baseTournamentPersonnel.getUserId());
            queryWrapper.eq(BaseTournamentPersonnel::getContestId, baseTournamentPersonnel.getContestId());
            queryWrapper.last("limit 1");

            BaseTournamentPersonnel personnel = baseMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotNull(personnel)) {
                return -1;
            }
        }
        iBaseUserOrganizationService.savePO(SecurityUtils.getOrganizationId(),info.getUserId());
        baseTournamentPersonnel.setUserId(info.getUserId());
        baseTournamentPersonnel.setCreateTime(DateUtils.getNowDate());
        return baseTournamentPersonnelMapper.insertBaseTournamentPersonnel(baseTournamentPersonnel);
    }
    public static Long getUserIds() {
        long timestamp = System.currentTimeMillis();
        Random random = new Random();
        int randomNumber = random.nextInt(9000)+1000;
        int checksum = (int)((timestamp + randomNumber) %10);
        String id = String.format("%d%d%d",timestamp,randomNumber,checksum);
        return Long.parseLong(id);
    }
    /**
     * 修改赛事工作人员
     * 
     * @param baseTournamentPersonnel 赛事工作人员
     * @return 结果
     */
    @Override
    public int updateBaseTournamentPersonnel(BaseTournamentPersonnel baseTournamentPersonnel)
    {
        BaseTournamentPersonnel tournamentPersonnel = selectBaseTournamentPersonnelById(baseTournamentPersonnel.getId());
        //数据不为空的情况
        if (ObjectUtil.isNotNull(tournamentPersonnel)) {
            //如果要修改的权限是联赛级别
            if (baseTournamentPersonnel.getLevel() != null && baseTournamentPersonnel.getLevel() == 0) {
                //校验当前userid是否存在其他权限
                LambdaQueryWrapper<BaseTournamentPersonnel> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BaseTournamentPersonnel::getUserId, baseTournamentPersonnel.getUserId());
                queryWrapper.eq(BaseTournamentPersonnel::getContestId, baseTournamentPersonnel.getContestId());
                queryWrapper.ne(BaseTournamentPersonnel::getId,baseTournamentPersonnel.getId());
                queryWrapper.last("limit 1");

                BaseTournamentPersonnel personnel = baseMapper.selectOne(queryWrapper);
                if (ObjectUtil.isNotNull(personnel)) {
                    return -1;
                }
            }

//            baseTournamentPersonnel.setUpdateTime(DateUtils.getNowDate());
            loginUserSetUtil.populateFields(baseTournamentPersonnel,2);
            return baseTournamentPersonnelMapper.updateBaseTournamentPersonnel(baseTournamentPersonnel);
        }
        return -1;
    }

    /**
     * 批量删除赛事工作人员
     * 
     * @param ids 需要删除的赛事工作人员主键
     * @return 结果
     */
    @Override
    public int deleteBaseTournamentPersonnelByIds(Long[] ids)
    {
//        Long id = ids[0];
//        BaseTournamentPersonnel one = this.getById(id);
//        if (Objects.nonNull(one)){
//
//            iBaseUserOrganizationService.deleteUserOrganization(one.getOrganizationId(),one.getUserId());
//        }
        return baseTournamentPersonnelMapper.deleteBaseTournamentPersonnelByIds(ids);
    }

    /**
     * 删除赛事工作人员信息
     * 
     * @param id 赛事工作人员主键
     * @return 结果
     */
    @Override
    public int deleteBaseTournamentPersonnelById(Long id)
    {
        return baseTournamentPersonnelMapper.deleteBaseTournamentPersonnelById(id);
    }

    /**
     * 出勤统计
     *
     * @param seasonId
     * @return
     */
    @Override
    public List<BaseTournamentPersonnelResponseVO> getAttendanceCount(Long seasonId) {

        //拿到所有出勤记录
        List<BaseTournamentPersonnelAttendanceVO> attendanceVO = baseMapper.getAttendanceCount(seasonId);

        List<BaseTournamentPersonnelResponseVO> responseVOList = new ArrayList<>();

        if (CollectionUtil.isEmpty(attendanceVO)){
            return responseVOList;
        }
        //以用户纬度分组处理
        Map<Long, List<BaseTournamentPersonnelAttendanceVO>> listMap = attendanceVO.stream().collect(Collectors.groupingBy(BaseTournamentPersonnelAttendanceVO::getUserId));
        //处理数据
        listMap.forEach((k,v) -> {
            BaseTournamentPersonnelResponseVO responseVO = new BaseTournamentPersonnelResponseVO();
            responseVO.setUserId(k);
            v.forEach( item->{
                switch (item.getType()){
                    case 1:
                        responseVO.setOne(item.getCountPerType());
                        break;
                    case 2:
                        responseVO.setTwo(item.getCountPerType());
                        break;
                    case 3:
                        responseVO.setThree(item.getCountPerType());
                        break;
                    case 4:
                        responseVO.setFour(item.getCountPerType());
                        break;
                }
                responseVO.setNickName(item.getNickName());

            });
            responseVOList.add(responseVO);
        });

        return responseVOList;
    }
}
